<template>
  <n-grid :cols="24">
    <n-grid-item span="24">
      <detail-page-header title="产品详情">
        <div>
          <n-button type="primary" @click.stop="handleSubmit">保存</n-button>
        </div>
      </detail-page-header>
      <div class="mt-[16px]"></div>
      <n-grid :col="24" x-gap="10">
        <n-grid-item span="12">
          <n-card>
            <n-h3>产品信息</n-h3>
            <n-form ref="formRef" :model="modelForm">
              <n-row :gutter="10">
                <n-col :span="24">
                  <n-form-item label="产品名称" path="name">
                    <n-input
                      v-model:value="modelForm.name"
                      placeholder="请输入产品名称"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="产品分类" path="categoryId">
                    <n-select
                      v-model:value="modelForm.categoryId"
                      value-field="id"
                      label-field="name"
                      clearable
                      :options="categories"
                      placeholder="请选择产品分类"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="品牌" path="brandId">
                    <n-select
                      v-model:value="modelForm.brandId"
                      value-field="id"
                      label-field="name"
                      clearable
                      :options="brands"
                      placeholder="请选择品牌"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="24">
                  <n-form-item label="状态" path="status">
                    <n-switch
                      :checked-value="'1'"
                      :unchecked-value="'2'"
                      v-model:value="modelForm.status"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="产品封面">
                    <n-upload
                      :headers="headers"
                      v-model:file-list="coverFileList"
                      response-type="json"
                      :max="1"
                      list-type="image-card"
                      :action="`${uploadUrl}?biz=product-avatar`"
                      @finish="handleUploadFinishCover"
                      @remove="handleUploadRemoveCover"
                    >
                      点击上传
                    </n-upload>
                  </n-form-item>
                </n-col>
                <n-col :span="12">
                  <n-form-item label="产品图片">
                    <n-upload
                      :headers="headers"
                      v-model:file-list="galleryFileList"
                      response-type="json"
                      :max="5"
                      list-type="image-card"
                      :action="`${uploadUrl}?biz=product-gallery`"
                      @remove="handleRemoveGallery"
                      @finish="handleUploadFinishGallery"
                    >
                      点击上传
                    </n-upload>
                  </n-form-item>
                </n-col>
                <n-col :span="24">
                  <n-form-item label="附加属性">
                    <n-space>
                      <n-checkbox
                        v-model:checked="modelForm.canTradein"
                        :checked-value="'1'"
                        :unchecked-value="'0'"
                      >
                        可回收
                      </n-checkbox>
                      <n-checkbox
                        disabled
                        v-model:checked="modelForm.hasVariant"
                        :checked-value="'1'"
                        :unchecked-value="'0'"
                      >
                        多SKU
                      </n-checkbox>
                      <n-checkbox
                        v-model:checked="modelForm.canRepairable"
                        :checked-value="'1'"
                        :unchecked-value="'0'"
                      >
                        可维修
                      </n-checkbox>
                      <n-checkbox
                        disabled
                        :checked-value="'1'"
                        :unchecked-value="'0'"
                      >
                        有序列号
                      </n-checkbox>
                    </n-space>
                  </n-form-item>
                </n-col>
                <template v-if="modelForm.hasVariant === '1'">
                  <n-col :span="24">
                    <n-divider title-placement="left"> SKU属性 </n-divider>
                  </n-col>
                  <n-col :span="24">
                    <n-table :bordered="true">
                      <thead>
                        <tr>
                          <th>属性</th>
                          <th>属性值</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="attr in modelForm.attributes" :key="attr.id">
                          <td>{{ attr.label }}</td>
                          <td>
                            <n-space>
                              <n-tag
                                v-for="attrValue in attr.data"
                                :key="attrValue.attributeValueId"
                              >
                                {{ attrValue.label }}
                              </n-tag>
                            </n-space>
                          </td>
                        </tr>
                      </tbody>
                    </n-table>
                  </n-col>
                </template>
                <template v-if="modelForm.hasVariant !== '1'">
                  <n-col :span="24">
                    <n-divider title-placement="left"> 价格配置 </n-divider>
                  </n-col>
                  <n-col :span="12">
                    <n-form-item label="原价" path="originalPrice">
                      <n-input-number
                        class="w-full"
                        clearable
                        placeholder="请输入原价"
                        v-model:value="modelForm.originalPrice"
                      />
                    </n-form-item>
                  </n-col>

                  <n-col :span="12">
                    <n-form-item label="成交价" path="currentPrice">
                      <n-input-number
                        class="w-full"
                        clearable
                        placeholder="请输入成交价"
                        v-model:value="modelForm.currentPrice"
                      />
                    </n-form-item>
                  </n-col>
                </template>
                <n-col :span="24">
                  <n-divider title-placement="left"> 可选配置 </n-divider>
                </n-col>
                <template v-if="modelForm.hasVariant !== '1'">
                  <n-col :span="12">
                    <n-form-item label="SKU" path="sku">
                      <n-input
                        clearable
                        placeholder="请输入SKU"
                        v-model:value="modelForm.sku"
                      />
                    </n-form-item>
                  </n-col>
                  <n-col :span="12">
                    <n-form-item label="重量" path="weight">
                      <n-input-number
                        class="w-full"
                        clearable
                        placeholder="请输入重量"
                        v-model:value="modelForm.weight"
                      />
                    </n-form-item>
                  </n-col>
                </template>
                <n-col :span="24">
                  <n-form-item label="排序" path="sort">
                    <n-input-number
                      class="w-full"
                      clearable
                      placeholder="请输入排序"
                      v-model:value="modelForm.sort"
                    />
                  </n-form-item>
                </n-col>
                <n-col :span="24">
                  <n-form-item label="描述" path="description">
                    <n-input
                      placeholder="请输入描述"
                      type="textarea"
                      v-model:value="modelForm.description"
                    />
                  </n-form-item>
                </n-col>
              </n-row>
            </n-form>
          </n-card>
        </n-grid-item>
        <n-grid-item span="12">
          <n-card>
            <template #header>
              <div class="flex items-center">
                <span>SKU列表</span>

                <n-button circle quaternary class="ml-2" @click="toggleFileter">
                  <template #icon>
                    <n-icon><FilterSharp /></n-icon>
                  </template>
                </n-button>
              </div>
            </template>
            <template #header-extra>
              <n-button type="primary" @click.stop="handleNavToVariants"
                >快速修改</n-button
              >
            </template>
            <n-space vertical>
              <n-card
                size="small"
                v-for="variant in variantsTableResult.dataList"
                :key="variant.id"
                :title="variant.name"
              >
                <template #header-extra>
                  <n-button quaternary size="small">
                    <template #icon>
                      <n-icon><CreateOutline /></n-icon>
                    </template>
                  </n-button>
                </template>
                <div class="mt-2 flex justify-between">
                  <n-tag>{{ variant.sku }}</n-tag>
                  <n-tag :type="variant.status === '1' ? 'info' : 'error'">
                    {{ variant.status === "1" ? "启用" : "禁用" }}
                  </n-tag>
                </div>
                <div class="mt-2">
                  <n-table>
                    <thead>
                      <tr>
                        <th>建议零售价</th>
                        <th>促销价</th>
                        <template v-if="canTradeIn">
                          <th>建议回收价</th>
                          <th>最低回收价</th>
                        </template>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td>{{ variant.soldPrice || "0" }}</td>
                        <td>{{ variant.promotionPrice || "0" }}</td>
                        <template v-if="canTradeIn">
                          <td>{{ variant.recTradeinPrice || "0" }}</td>
                          <td>{{ variant.minTradeinPrice || "0" }}</td>
                        </template>
                      </tr>
                    </tbody>
                  </n-table>
                </div>
              </n-card>
            </n-space>
            <div class="mt-2 flex flex-1 justify-end">
              <n-pagination
                simple
                :page-count="variantsTableResult.pageCount"
                v-model:page="variantQueryForm.page"
                @update:page="handleVariantsPageChange"
              />
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>
    </n-grid-item>
  </n-grid>
  <!-- 过滤条件 -->
  <filter-modal
    title="SKU过滤条件"
    v-model:show="showFilter"
    :allConditions="allConditaions"
    :selectedConditions="selectedConditions"
    @confirm="handleFilterConfirm"
  />
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { FormInst, UploadFileInfo, useMessage } from "naive-ui";
import { CreateOutline, FilterSharp } from "@vicons/ionicons5";
import { cloneDeep, debounce, get, groupBy, isArray } from "lodash-es";
import { getCategories } from "@/api/product/category.api";
import { getBrands } from "@/api/product/brand.api";
import {
  getProductById,
  updateProduct,
  getVariantsByPage,
} from "@/api/product/product.api";
import {
  getAllAttributes,
  getAttributeByProductId,
} from "@/api/product/productAttribute.api";
import { Category } from "@/types/model/product/vos/category.vo";
import { BULK_UPDATE_VARIANTS_PAGE } from "@/router/routerNames/index";
import { getHeaders } from "@/common/utils/comps/index";
import { uploadUrl } from "@/api/basic/basic.api";
import { useFilter } from "@/components/normal/filterModal/hooks";
import { IProductDetailProps } from "./props";

const headers = getHeaders();
const message = useMessage();
const router = useRouter();
const { selectedConditions, allConditaions, showFilter, toggleFileter } =
  useFilter();

const props = defineProps<IProductDetailProps>();

const formRef = ref<FormInst | null>(null);
const pageLoading = ref<boolean>(false);
const categories = ref<Category[]>([]);
const brands = ref<any>([]);
const attributes = ref<any[]>([]);
const productDetail = ref<any>({});

const coverFileList = ref<UploadFileInfo[]>([]);
const galleryFileList = ref<UploadFileInfo[]>([]);

const variantsTableResult = reactive({
  loading: false,
  dataList: [] as any[],
  total: 0,
  pageCount: 1,
});

const variantQueryForm = reactive({
  page: 1,
  pageSize: 5,
});

const modelForm = reactive({
  id: "",
  name: "",
  categoryId: undefined,
  brandId: undefined,
  sort: 0,
  slug: "",
  image: "",
  status: undefined,
  originalPrice: 0,
  currentPrice: 0,
  tag: "",
  sku: "",
  weight: undefined,
  description: "",
  canTradein: "0",
  hasSerialNumber: "0",
  hasVariant: "0",
  canRepairable: "0",
  attributes: [] as any[],
  deleteGallery: [] as any[],
  newGallery: [] as any[],
  newGalleryFileList: [] as UploadFileInfo[],
});

const canTradeIn = computed(() => {
  const _canTradein = get(modelForm, "canTradein") || "0";
  return _canTradein === "1";
});

const handleNavToVariants = () => {
  router.push({
    name: BULK_UPDATE_VARIANTS_PAGE.NAME,
    params: {
      prodcutId: props.id,
    },
  });
};

const getAttributeName = (attributeId: string) => {
  const _attribute = attributes.value.find((item) => item.id === attributeId);
  return get(_attribute, "name") || "";
};

const getAttributeValueName = (attributeId: string, attrValuId: string) => {
  const _attribute = attributes.value.find((item) => item.id === attributeId);
  if (isArray(_attribute?.values)) {
    const _attrValue = _attribute.values.find(
      (valueItem: any) => valueItem.id === attrValuId
    );
    return get(_attrValue, "name") || "";
  } else {
    return "";
  }
};

const handleGetAllAttributes = async () => {
  const res = await getAllAttributes();
  attributes.value = get(res, "result") || [];
};

const handleGetCategories = async () => {
  const res = await getCategories({
    page: 1,
    pageSize: 1000,
    status: "1",
  });
  categories.value = get(res, "result.records") || [];
};

const handleGetBrands = async () => {
  const res = await getBrands({
    page: 1,
    pageSize: 1000,
    status: "1",
  });
  brands.value = get(res, "result.records") || [];
};

const handleGetProductDetail = async (productId: string) => {
  pageLoading.value = true;
  try {
    const res = await getProductById(productId);
    const _productDetail = get(res, "result") || {};

    const _attributes = get(_productDetail, "attributes") || [];
    if (isArray(_attributes) && _attributes.length) {
      const attributesGroupByAttId = groupBy(_attributes, "attributeId");
      const groupByAttrList = [];
      for (const key in attributesGroupByAttId) {
        const attrList = attributesGroupByAttId[key];

        const attrValueListMap = new Map();

        attrList.forEach((item) => {
          if (!attrValueListMap.has(item.attributeValueId)) {
            attrValueListMap.set(item.attributeValueId, item);
          }
        });

        const obj = {
          id: key,
          label: getAttributeName(key),
          value: key,
          data: [...attrValueListMap.values()].map((item) => {
            return {
              ...item,
              label: getAttributeValueName(key, item.attributeValueId),
              value: item.attributeValueId,
            };
          }),
        };
        groupByAttrList.push(obj);
        selectedConditions.value[key] = obj.data.map((item) => item.value);
      }

      allConditaions.value = cloneDeep(groupByAttrList);
      modelForm.attributes = cloneDeep(groupByAttrList);
    }

    const coverUrl = get(_productDetail, "image") || "";

    productDetail.value = cloneDeep(_productDetail);
    modelForm.id = get(_productDetail, "id");
    modelForm.name = get(_productDetail, "name");
    modelForm.categoryId = get(_productDetail, "categoryId");
    modelForm.brandId = get(_productDetail, "brandId");
    modelForm.sort = get(_productDetail, "sort");
    modelForm.status = get(_productDetail, "status");
    modelForm.originalPrice = get(_productDetail, "originalPrice");
    modelForm.currentPrice = get(_productDetail, "currentPrice");
    modelForm.sku = get(_productDetail, "sku");
    modelForm.weight = get(_productDetail, "weight");
    modelForm.description = get(_productDetail, "description");
    modelForm.canTradein = get(_productDetail, "canTradein");
    modelForm.hasSerialNumber = get(_productDetail, "hasSerialNumber");
    modelForm.hasVariant = get(_productDetail, "hasVariant");
    modelForm.canRepairable = get(_productDetail, "canRepairable");
    modelForm.image = coverUrl;

    if (coverUrl) {
      resolveCover(coverUrl);
    }

    const gallery = get(_productDetail, "gallery") || [];
    if (gallery && gallery.length) {
      resolveGallery(gallery);
    }
  } catch (e) {
  } finally {
    pageLoading.value = false;
  }
};

const handleGetVariantsByPage = async (selectedConditions?: string[]) => {
  variantsTableResult.loading = true;
  try {
    let params: any = {
      productId: props.id,
      pageNo: variantQueryForm.page,
      pageSize: variantQueryForm.pageSize,
    };
    if (selectedConditions && selectedConditions.length) {
      params.attributeValueIds = selectedConditions;
    }
    const result = await getVariantsByPage(params);
    variantsTableResult.total = get(result, "result.total");
    variantsTableResult.dataList = get(result, "result.records") || [];
    variantsTableResult.pageCount = get(result, "result.pages");
  } finally {
    variantsTableResult.loading = false;
  }
};

const handleVariantsPageChange = debounce(function () {
  handleGetVariantsByPage();
}, 200);

const resolveCover = (coverUrl: string) => {
  if (coverUrl) {
    coverFileList.value = [
      {
        id: "cover",
        status: "finished",
        name: coverUrl,
        url: coverUrl,
      },
    ];
  }
};

const handleUploadFinishCover = (payload: any) => {
  console.log(payload);
  const url = get(payload, "event.target.response.message") || "";
  if (url) {
    modelForm.image = url;
  }
};

const handleUploadRemoveCover = (_: any) => {
  modelForm.image = "";
};

const resolveGallery = (gallery: any[]) => {
  if (isArray(gallery) && gallery.length) {
    galleryFileList.value = gallery.map((item) => {
      return {
        id: item.id,
        status: "finished",
        name: item.imageUrl,
        url: item.imageUrl,
      };
    });
  }
};

const handleRemoveGallery = (payload: any) => {
  console.log(payload);
  const fileId = get(payload, "file.id") || "";
  if (fileId) {
    const originalGallery = get(productDetail.value, "gallery") || [];
    if (originalGallery && originalGallery.length) {
      const targetFile = originalGallery.find(
        (originalItem: any) => originalItem.id === fileId
      );
      if (targetFile) {
        // 不是原有的
        modelForm.deleteGallery.push(fileId);
      } else {
        // 删除新增的
        modelForm.newGalleryFileList = modelForm.newGalleryFileList.filter(
          (item) => item.id !== fileId
        );
      }
    }
  }
};

const handleUploadFinishGallery = (payload: any) => {
  const url = get(payload, "event.target.response.message") || "";
  const id = get(payload, "file.id") || "";
  const name = get(payload, "file.name") || "";
  modelForm.newGalleryFileList.push({
    id,
    name,
    url,
    status: "finished",
  });
};

const handleSubmit = async () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }

    const params = {
      id: modelForm.id,
      status: modelForm.status,
      name: modelForm.name,
      description: modelForm.description,
      categoryId: modelForm.categoryId,
      brandId: modelForm.brandId,
      canTradein: modelForm.canTradein,
      canRepairable: modelForm.canRepairable,
      image: modelForm.image,
      sort: modelForm.sort,
      deleteGallery: modelForm.deleteGallery,
      newGallery: modelForm.newGalleryFileList.map(
        (item) => item.url
      ) as string[],
    };

    updateProduct(params).then((res) => {
      console.log(res);
    });
  });
};

const handleFilterConfirm = async (_selectedConditions: any) => {
  // let attrValueIds: string[] = [];
  // [...Object.values(_selectedConditions)].forEach((item: any) => {
  //   attrValueIds = attrValueIds.concat(item);
  // });
  // handleGetVariantsByPage(attrValueIds);
};

const init = async () => {
  await handleGetAllAttributes();
  handleGetCategories();
  handleGetBrands();
  handleGetProductDetail(props.id);
  handleGetVariantsByPage();
  getAttributeByProductId(props.id).then((res) => {
    console.log("====");
    console.log(res);
  });
};

onMounted(() => {
  init();
});
</script>
